package com.bifrost.web.controller;

import com.bifrost.service.CustomerService;
import com.bifrost.wechat.service.WxServiceContext;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author joewee
 */
@Controller
@RequestMapping("{code}/index")
public class CbestIndexController {
    private static final Logger LOGGER = LoggerFactory.getLogger(CbestIndexController.class);
    @Value("${wechat.oauth2.redirect.url:#{null}}")
    private String redirect_url;
    @Autowired
    private WxServiceContext wxServiceContext;

    @RequestMapping()
    public String index(@PathVariable("code")String code, HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        if(session!=null){
            //失效之前的session
            session.invalidate();
        }
        if (StringUtils.isEmpty(code)) {
            response.setStatus(404);
            return "";
        }else{
            WxMpService wxService = wxServiceContext.getWxServiceByStoreCode(code);
            String url = wxService.oauth2buildAuthorizationUrl(String.format("%s/%s",redirect_url,code), "snsapi_userinfo", String.format("/index.html?"));
            return "redirect:"+url;
        }
    }
}
